// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'
import router from './router'
import './css/common.css';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

import VueQuillEditor  from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import store from './store'

import axios from 'axios'
import user from "./store/module/user";
Vue.prototype.$axios = axios;


Vue.use(VueRouter)
Vue.use(ElementUI);
Vue.use(VueQuillEditor);

//拦截请求
router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
    const token = store.getters.getUserToken;
    if (token) {  // 通过vuex state获取当前的token是否存在
      next();
    }
    else {
      next({
        path: '/login',
        query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  }
  else {
    next();
  }
})
//请求拦截
axios.interceptors.request.use(
  config => {

    const token = store.getters.getUserToken;
    config.data = JSON.stringify(config.data);

    if(token){
      config.headers = {
        'Content-Type':'application/json; charset=utf-8',
        'Authorization':token
      };
    }else{
      config.headers = {
        'Content-Type':'application/json; charset=utf-8'
      };
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

//响应拦截
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          this.$message.error(error.response.data);
      }
    }
    return Promise.reject(error.response);
  });


new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
